<template>
  <Page name="个人收钱" :loading="loading" theme="white">
    <nuxt-link to="/recv/list?idx=0" slot="right" class="header-link">收款记录</nuxt-link>

    <div class="page-recv-wrap">
      <div class="recv-box fxv-center">
        <p class="tit">使用乐马支付扫一扫，向我付款</p>
        <div class="qrcode">
            <div id="qrcode-wrap"></div>
          <!-- <img :src="`data:image/png;base64,${info.qrcode}`" v-if="info.qrcode" ref="qrcode"> -->
          <div class="avatar">
            <img v-if="avatar" :src="avatar" class="avatar">
            <img v-else src="~assets/img/ic_mine_profile.png">
          </div>
        </div>
        <div class="set" v-if="params.amount && params.currency_code">
          <div class="total fx">
            <div class="price">{{params.amount}}</div>
            <div class="currency">{{params.currency_code}}</div>
          </div>
          <div class="label">{{params.remark}}</div>
        </div>
        <div class="action fx fx-between">
          <div class="text-primary" @click="setPrice">{{params.amount && params.currency_code ? '清除金额' : '设置金额'}}</div>
          <div class="text-primary" @click="savePhoto">保存图片</div>
        </div>
      </div>
    </div>
  </Page>
</template>

<script>
import Page from '~/components/page'
import QRCode from '~/plugins/qrcode';
/**该方法用来绘制圆角矩形
*@param cxt:canvas的上下文环境
*@param x:左上角x轴坐标
*@param y:左上角y轴坐标
*@param width:矩形的宽度
*@param height:矩形的高度
*@param radius:圆的半径
*@param lineWidth:线条粗细
*@param strokeColor:线条颜色
**/
function fillRoundRect(cxt,x,y,width,height,radius,/*optional*/fillColor){
    //圆的直径必然要小于矩形的宽高
    if(2*radius>width || 2*radius>height){return false;}

    cxt.save();
    cxt.translate(x,y);
    //绘制圆角矩形的各个边
    drawRoundRectPath(cxt,width,height,radius);
    cxt.fillStyle=fillColor||"#000";//若是给定了值就用给定的值否则给予默认值
    cxt.fill();
    cxt.restore();
}

function strokeRoundRect(cxt,x,y,width,height,radius,/*optional*/lineWidth,/*optional*/strokeColor){
    //圆的直径必然要小于矩形的宽高
    if(2*radius>width || 2*radius>height){return false;}

    cxt.save();
    cxt.translate(x,y);
    //绘制圆角矩形的各个边
    drawRoundRectPath(cxt,width,height,radius);
    cxt.lineWidth = lineWidth||2;//若是给定了值就用给定的值否则给予默认值2
    cxt.strokeStyle=strokeColor||"#000";
    cxt.stroke();
    cxt.restore();
}

function drawRoundRectPath(cxt,width,height,radius){
    cxt.beginPath(0);
    //从右下角顺时针绘制，弧度从0到1/2PI
    cxt.arc(width-radius,height-radius,radius,0,Math.PI/2);

    //矩形下边线
    cxt.lineTo(radius,height);

    //左下角圆弧，弧度从1/2PI到PI
    cxt.arc(radius,height-radius,radius,Math.PI/2,Math.PI);

    //矩形左边线
    cxt.lineTo(0,radius);

    //左上角圆弧，弧度从PI到3/2PI
    cxt.arc(radius,radius,radius,Math.PI,Math.PI*3/2);

    //上边线
    cxt.lineTo(width-radius,0);

    //右上角圆弧
    cxt.arc(width-radius,radius,radius,Math.PI*3/2,Math.PI*2);

    //右边线
    cxt.lineTo(width,height-radius);
    cxt.closePath();
}


export default {
  components:{
    Page
  },
  asyncData({route}){
    if(route.params){
      return { params:route.params};
    }
  },
  data(){
    return {
      loading:false,
      avatar:'',
      info:{},
      params:{}
    }
  },
  async mounted(){
    document.documentElement.classList.add('bg-primary')
    //加载图片成功则显示
    if(this.$store.state.user.avatar){
      let img = new Image;
      img.src = this.$store.state.user.avatar;
      img.onload = ()=>{
        this.avatar = this.$store.state.user.avatar;
      }
    }
    // 获取收款码
    await this.getRecvCode();
  },
  destroyed(){
    document.documentElement.classList.remove('bg-primary')
  },
  methods:{
    async setPrice(){
      if(this.info.amount && this.info.currency_code){
        this.info = {}
        this.params = {}
        await this.getRecvCode();
      }else{
        this.$router.push('/recv/set')
      }
    },
    async getRecvCode(){ // 获取收款码
      try{
        if(this.loading) return false;
        this.loading = true;
        // this.$nuxt.$loading.start();
        let { data: rs } = await this.$axios.post('?ct=api&ac=recv_url',this.params);
        if(rs.code == 0){
          const {data} = rs;
          let qrcode = new QRCode('qrcode-wrap', {
            text: data.code_url,
            width: 400,
            height: 400,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRCode.CorrectLevel.L
          });
          this.info = rs.data;
        }else{
          this.$toast(rs.msg);
        }
      }catch(e){
        this.$error(e);
      }
      this.loading = false;
      // this.$nuxt.$loading.finish()
    },
    savePhoto(){ //下载图片
      let img = document.querySelector('#qrcode-wrap>img');
      if(!img){
        this.$alert('生成二维码失败');
        return false;
      }
      this.qrcode2Img();
      // this.downloadFile('qrcode.png',`data:image/png;base64,${this.info.qrcode}`);
    },
    qrcode2Img(){ //合成图片下载
      let img = document.querySelector('#qrcode-wrap>img');
      let canvas = document.createElement('canvas');
      canvas.width = img.clientWidth;
      canvas.height = img.clientHeight;
      let ctx = canvas.getContext('2d');
      ctx.rect(0,0,canvas.width,canvas.height);
      ctx.fillStyle='#fff';
      ctx.fill();
      //加载二维码
      ctx.drawImage(img,0,0,canvas.width,canvas.width);
      //画补白
      let avatarBox = document.querySelector('.avatar');
      if(avatarBox){
        let w = avatarBox.clientWidth;
        let h = avatarBox.clientHeight;
        fillRoundRect(ctx,(canvas.width - w)/2,(canvas.height - h)/2,w,h,10,'ffffff');

        //添加用户头像
        let img = document.querySelector('.avatar>img');
        if(img){
          img.crossOrigin = 'Anonymous';
          let aw = img.clientWidth;
          let ah = img.clientHeight;
          ctx.drawImage(img,(canvas.width - aw)/2,(canvas.height - ah)/2,aw,ah);
        }
      }

      let base64 = canvas.toDataURL("image/jpeg")
      this.downloadFile('lm_qrcode.jpg',base64)

    },
    downloadFile(fileName, content) {
        let aLink = document.createElement('a');
        let blob = this.base64ToBlob(content); //new Blob([content]);
        let evt = document.createEvent("HTMLEvents");
        evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
      },
      //base64转blob
      base64ToBlob(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;

        let uInt8Array = new Uint8Array(rawLength);

        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {type: contentType});
      },
  }
}
</script>

<style lang="less" scoped>
.header-link {
  position: absolute;
  top:0;
  right:0;
  height:100%;
  padding:0 30px;
  color:#fff;
  font-size:30px;
}
.page-recv-wrap {
  color:#292929;
  padding:30px;
  background-color:#2086f9;
   .tit {
     font-size:28px;
   }
  .recv-box {
    padding:100px 80px 80px;
    background-color:#fff;
    border-radius: 10px;

    .qrcode {
      margin-top:74px;
      position: relative;
      width:392px;
      height:392px;

      /deep/ * {
        img,#qrcode-wrap,canvas {
          display: block;
          width: 100%;
          height:100%;
        }
      }
      .avatar {
        position: absolute;
        top:50%;
        left:50%;
        transform: translate(-50%,-50%);
        width:68px;
        height: 68px;
        padding:4px;
        background-color: #fff;
        overflow: hidden;
        border-radius: 10px;
      }
    }
    .set {
      margin-top:30px;
      max-width:100%;
      .total {
        align-items: flex-end;
        justify-content: center;
      }
      .label {
        word-break: break-all;
        text-align: center;
        margin-top:30px;
        font-size:28px;
        line-height: 1.2;
        color:#666666;
      }
    }
    .price {
      font-size:42px;
      // flex:1;
      .text-ellipsis();
    }

    .currency {
      font-size:30px;
      margin-left:16px;
    }
    .action {
      width:392px;
      font-size:30px;
      color:#1d86f3;
      margin-top:40px;
    }
  }
}
</style>
